package com.sea.wechat.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

/**   
 * @ClassName:     AccessTokenUtil   
 * @Description:   获取token  
 * @author:        wl
 * @date:          2017年8月3日 上午11:28:25     
 */ 
public class AccessTokenUtil {

	private static final Logger logger = LoggerFactory.getLogger(AccessTokenUtil.class);
	
	
	/**   
	 * @Title:         getToken   
	 * @Description:   判断token是否存在  
	 * @param:         @return      
	 * @return:        String   
	 * @author:        wl  
	 * @date:          2017年8月2日 下午6:55:16   
	 */  
	public static String getToken() {
		if(JedisUtil.exists(RedisKey.ACCESS_TOKEN)){
			return JedisUtil.get(RedisKey.ACCESS_TOKEN);
		}else {
			StringBuilder url = new StringBuilder();
			url.append(ResourceUtil.getGETACCESSTOKENURL());
			url.append("appid="+ResourceUtil.getAPPID()+"&secret="+ResourceUtil.getAPPSECRET());
			logger.info("getAccessToken:请求地址====="+url.toString());
			String result = HttpUtils.HttpURLConnectionGet(url.toString(), null);
			JSONObject obj = JSONObject.parseObject(result);
			if(obj.containsKey(RedisKey.ACCESS_TOKEN)){
				//将token存入redis中,保存两个小时
				JedisUtil.setex(RedisKey.ACCESS_TOKEN, obj.getString(RedisKey.ACCESS_TOKEN), 60*60*2);
				return obj.getString(RedisKey.ACCESS_TOKEN);
			}else {
				return result;
			}
		}
	}
	
	/**   
	 * @Title:         getJsapiTicket   
	 * @Description:   获取js-ticket票据  
	 * @param:         @return      
	 * @return:        String   
	 * @author:        wl  
	 * @date:          2017年8月13日 下午3:08:10   
	 */  
	public static String getJsapiTicket(){
		//判断redis是否有票据，有的话直接返回，没有查询后存入redis然后返回票据
		if(JedisUtil.exists(RedisKey.JSAPI_TICKET)){
			return JedisUtil.get(RedisKey.JSAPI_TICKET);
		}else {
			StringBuffer url = new StringBuffer();
			url.append(ResourceUtil.GETJSAPITICKET);
			url.append(getToken());
			url.append("&type=jsapi");
			logger.info("getJsapiTicket:请求地址====="+url.toString());
			String result = HttpUtils.HttpURLConnectionGet(url.toString(), null);
			JSONObject obj = JSONObject.parseObject(result);
			if(obj.containsKey(RedisKey.JSAPI_TICKET)){
				//将token存入redis中,保存两个小时
				JedisUtil.setex(RedisKey.JSAPI_TICKET, obj.getString(RedisKey.JSAPI_TICKET), 60*60*2);
				return obj.getString(RedisKey.JSAPI_TICKET);				
			}else {
				return result;
			}
		}
	}
}
